<style lang="stylus" scoped>
  .user-logo-border
    border 1px solid $grey-4
    border-radius 4px

</style>

<template>
  <div>
    <q-table
      class="bg-white shadow-1"
      :data="data"
      dense
      :columns="columns"
      row-key="id"
      separator="cell"
      selection="multiple"
      :selected.sync="selected"
      :visible-columns="visibleColumns"
      :filter="searchForm"
      :pagination.sync="pagination"
      :rows-per-page-options="[3, 5, 10, 20]"
      no-data-label="暂无数据"
      table-class="h-custom"
      @request="listGet"
    >
      <template v-slot:top-left="props">
        <q-btn size="sm" color="light-blue" :label="$t('新增')" @click="add"/>
        <!-- <q-btn color="negative" flat :label="$t('批量删除')" class="q-ml-sm"/> -->
      </template>
      <template v-slot:top-right="props">
        <q-select
          v-model="visibleColumns"
          multiple
          borderless
          options-dense
          :display-value="$t('显示列')"
          emit-value
          map-options
          :options="columns"
          option-value="name"
          class="q-mx-lg"
        >
          <template v-slot:option="scope">
            <q-item
              v-bind="scope.itemProps"
              v-on="scope.itemEvents"
              v-if="!scope.opt.required"
            >
              <q-item-section avatar>
                <q-toggle color="blue" v-model="visibleColumns" :val="scope.opt.name" />
              </q-item-section>
              <q-item-section style="min-width:60px">
                {{ scope.opt.label }}
              </q-item-section>
            </q-item>
          </template>
        </q-select>
        <q-toggle
          v-model="searchToggle"
          left-label
          label="搜索"
          color="blue"
          checked-icon="check"
          unchecked-icon="clear"
          keep-color
        />
        <q-btn
          flat round dense
          :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
          @click="props.toggleFullscreen"
          class="q-ml-md"
        />
      </template>
      <template v-if="searchToggle" v-slot:top-row="props">
        <q-tr :props="props">
          <q-td>
          </q-td>
          <q-td v-for="col in props.cols" :key="col.name" class="relative-position">
            <q-btn color="primary" dense flat icon="search" class="absolute-center" v-if="col.name==='action'" @click="listGet({ pagination: pagination, filter: searchFormGroup })"/>
            <q-input dense outlined v-model="searchForm[col.name]" v-else/>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th>
            <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
          </q-th>
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.label }}
          </q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td width="52">
            <q-checkbox dense v-model="props.selected" />
          </q-td>
          <q-td key="action" :props="props">
            <q-btn-dropdown
              color="blue"
              size="sm"
              dense
              menu-anchor="bottom left"
              menu-self="top left"
              content-class="text-grey"
              icon="settings">
              <q-list dense>
                <q-item clickable v-close-popup @click="edit(props.row)">
                  <q-item-section>
                    <q-item-label>修改</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup @click="delRow(props.row)">
                  <q-item-section>
                    <q-item-label>删除</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup @click="props.expand = !props.expand">
                  <q-item-section>
                    <q-item-label>{{ props.expand? '收起': '更多字段' }}</q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>
          </q-td>
          <q-td key="loginName" :props="props">{{ props.row.loginName }}</q-td>
          <q-td key="password" :props="props">{{ props.row.password }}</q-td>
          <q-td key="email" :props="props">{{ props.row.email }}</q-td>
          <q-td key="phone" :props="props">{{ props.row.phone }}</q-td>
          <q-td key="isNeedUpdatePassword" :props="props">{{ props.row.isNeedUpdatePassword }}</q-td>
          <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
        </q-tr>
        <q-tr v-show="props.expand" :props="props">
          <q-td colspan="100%">
          </q-td>
        </q-tr>
      </template>
      <template v-slot:pagination="props">
        <q-pagination
          v-model="pagination.page"
          color="blue"
          :max-pages="5"
          :max="pages"
          :boundaryLinks="true"
          :directionLinks="true"
        />
        共 {{ total }} 条
      </template>
    </q-table>
    <q-dialog
      v-model="addOrEditDialog"
      persistent
      :maximized="maximizedToggle"
      transition-show="slide-up"
      transition-hide="slide-down">
      <q-card class="bg-white relative-position" :style="{minWidth: addOrEditTab === 'tab1'?'40vw': '75vw'}">
        <q-bar class="bg-white q-py-lg">
          <strong>{{ addOrEdit === 1? '新增' : '修改'}}</strong>
          <q-space />
          <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
            <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
            <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="close" @click="addOrEditDialog = false">
            <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
          </q-btn>
        </q-bar>
        <q-separator />
        <q-card-section :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:50vh;max-height:60vh'" class="scroll">
          <q-tabs
            v-model="addOrEditTab"
            dense
            class="text-grey-9"
            active-color="primary"
            indicator-color="primary"
            align="left"
            :breakpoint="0"
            narrow-indicator
          >
            <q-tab name="tab1" label="用户信息" />
            <q-tab name="tab2" label="岗位和角色" :disable="!addOrEditForm.id"/>
          </q-tabs>
          <q-separator />
          <q-tab-panels v-model="addOrEditTab" animated>
            <q-tab-panel name="tab1" class="row q-col-gutter-sm">
              <div class="col-lg-4 col-md-4 col-sm-12 col-xs-12 row justify-center">
                <img
                  class="q-pa-sm user-logo-border"
                  src="~assets/default-profile-picture.png"
                  style="height:148px;width:148px"
                />
              </div>
              <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                <div :class="$v.addOrEditForm.loginName.$error?'text-negative': ''">账户</div>
                <q-input
                  v-model="addOrEditForm.loginName"
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForm.loginName.$error"
                  @blur="$v.addOrEditForm.loginName.$touch"
                  dense hint/>
                <div :class="$v.addOrEditForm.password.$error?'text-negative': ''">密码</div>
                <q-input
                  :disable="passwordDisable"
                  v-model="addOrEditForm.password"
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForm.password.$error"
                  @blur="$v.addOrEditForm.password.$touch"
                  dense hint/>
              </div>
              <div class="col-12">
                <div :class="$v.addOrEditForm.tenantId.$error?'text-negative': ''">所属租户</div>
                <q-select
                  emit-value
                  map-options
                  dense
                  :error="$v.addOrEditForm.tenantId.$error"
                  @blur="$v.addOrEditForm.tenantId.$touch"
                  v-model="addOrEditForm.tenantId"
                  :options="tenantOption" />
              </div>
              <div class="col-12">
                <div :class="$v.addOrEditForm.email.$error?'text-negative': ''">邮箱地址</div>
                <q-input
                  v-model="addOrEditForm.email"
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForm.email.$error"
                  @blur="$v.addOrEditForm.email.$touch"
                  dense hint/>
              </div>
              <!-- <div class="col-12">
                <div :class="$v.addOrEditForm.name.$error?'text-negative': ''">昵称</div>
                <q-input
                  v-model="addOrEditForm.name"
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForm.name.$error"
                  @blur="$v.addOrEditForm.name.$touch"
                  dense hint/>
              </div> -->
              <div class="col-12">
                <div :class="$v.addOrEditForm.phone.$error?'text-negative': ''">电话</div>
                <q-input
                  v-model="addOrEditForm.phone"
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForm.phone.$error"
                  @blur="$v.addOrEditForm.phone.$touch"
                  dense hint/>
              </div>
              <div class="col-12">
                <q-checkbox v-model="addOrEditForm.isNeedUpdatePassword" :true-value="1" :false-value="0" label="首次登录需要修改密码" color="light-blue">
                  <q-tooltip anchor="top middle" self="bottom middle" :offset="[5, 5]" content-class="bg-black text-white">
                    <div style="width:170px;font-size:11px">
                      在创建该用户后，首次登陆时需要修改密码。
                    </div>
                  </q-tooltip>
                </q-checkbox>
              </div>
            </q-tab-panel>

            <q-tab-panel name="tab2" class="row relative-position">
              <div v-if="isNodeSelected" class="absolute-right" style="top:20px;right:42px;z-index:9">
                <q-btn color="light-blue" :loading="saveUserRoleGroupLoading" label="保存" @click="saveUserRoleGroup">
                  <q-tooltip anchor="top middle" self="bottom middle" :offset="[5, 5]" content-class="bg-black text-white">
                    <div style="width:150px;font-size:11px">
                      保存为当前岗位所分配的角色和业务组。
                    </div>
                  </q-tooltip>
                </q-btn>
              </div>
              <div :class="[isNodeSelected ? 'col-lg-4 col-md-4' : 'col-lg-12 col-md-12', 'col-sm-12 col-xs-12']">
                <q-chip dense>
                  <q-avatar icon="bookmark" color="light-blue" text-color="white" />
                   点击组织架构树下岗位节点以分配角色和业务组
                </q-chip>
                <q-tree
                  ref="orgTree"
                  :nodes="nodes"
                  node-key="id"
                  label-key="name"
                  :selected.sync="nodeSelected"
                  selected-color="primary"
                  :expanded.sync="nodeExpanded"
                  tick-strategy="strict"
                  :ticked.sync="nodeTicked"
                  @update:selected="nodeSelectedHandler"
                >
                  <template v-slot:header-root="prop">
                    <div class="row items-center" style="width:100%">
                      <q-badge transparent align="middle" color="primary">
                        公司
                      </q-badge>
                      <div class="text-weight-bold ellipsis q-ml-xs" style="width:82%" :title="prop.node.code + ' - ' + prop.node.name">{{ prop.node.code + ' - ' + prop.node.name }}</div>
                    </div>
                  </template>

                  <template v-slot:header-company="prop">
                    <div class="row items-center" style="width:100%">
                      <q-badge transparent align="middle" color="secondary">
                        子公司
                      </q-badge>
                      <div class="ellipsis q-ml-xs" style="width:78%" :title="prop.node.code + ' - ' + prop.node.name">{{ prop.node.code + ' - ' + prop.node.name }}</div>
                    </div>
                  </template>

                  <template v-slot:header-dep="prop">
                    <div class="row items-center" style="width:100%">
                      <q-badge transparent align="middle" color="orange">
                        部门
                      </q-badge>
                      <div class="ellipsis q-ml-xs" style="width:74%" :title="prop.node.code + ' - ' + prop.node.name">{{ prop.node.code + ' - ' + prop.node.name }}</div>
                    </div>
                  </template>

                  <template v-slot:header-post="prop">
                    <div class="row items-center" style="width:100%" @click="nodeSelectedClick(prop.node.id)">
                      <q-badge transparent align="middle" color="positive">
                        岗位
                      </q-badge>
                      <div class="ellipsis q-ml-xs" style="width:74%" :title="prop.node.code + ' - ' + prop.node.name">{{ prop.node.code + ' - ' + prop.node.name }}</div>
                    </div>
                  </template>
                </q-tree>
              </div>
              <div v-if="isNodeSelected" :class="[isNodeSelected ? 'col-lg-8 col-md-8' : '', 'col-sm-12 col-xs-12']">
                <q-stepper
                  v-model="step"
                  vertical
                  flat
                  color="light-blue"
                  active-color="light-blue"
                  animated
                >
                  <q-step
                    :name="1"
                    title="角色"
                    icon="fas fa-user-tag"
                    active-icon="fas fa-user-tag"
                    @click="step = 1"
                  >
                    <q-table
                      flat
                      dense
                      class="bg-white"
                      :data="dataRole"
                      :columns="columnsRole"
                      row-key="roleId"
                      separator="cell"
                      selection="multiple"
                      :selected.sync="selectedRole"
                      :filter="searchFormRole"
                      :pagination.sync="paginationRole"
                      :rows-per-page-options="[3, 5, 10, 20]"
                      no-data-label="暂无数据"
                      table-class="h-custom"
                      @request="tableDataGet"
                    >
                      <template v-slot:header="props">
                        <q-tr :props="props" style="height:36px">
                          <q-th>
                            <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
                          </q-th>
                          <q-th v-for="col in props.cols" :key="col.name" :props="props">
                            {{ col.label }}
                          </q-th>
                        </q-tr>
                      </template>
                      <template v-slot:body="props">
                        <q-tr :props="props" style="height:36px">
                          <q-td width="52">
                            <q-checkbox dense v-model="props.selected" />
                          </q-td>
                          <q-td key="roleName" :props="props">{{ props.row.roleName }}</q-td>
                          <q-td key="roleCode" :props="props">{{ props.row.roleCode  }}</q-td>
                          <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
                        </q-tr>
                        <q-tr v-show="props.expand" :props="props">
                          <q-td colspan="100%">
                          </q-td>
                        </q-tr>
                      </template>
                      <template v-slot:pagination="props">
                        <!-- <q-pagination
                          v-model="paginationRole.page"
                          color="blue"
                          :max-pages="5"
                          :max="pagesRole"
                          :boundaryLinks="true"
                          :directionLinks="true"
                        /> -->
                        <q-pagination
                          v-model="paginationRole.page"
                          :max="pagesRole"
                          :input="true"
                        >
                        </q-pagination>
                        共 {{ totalRole }} 条
                      </template>
                    </q-table>
                  </q-step>

                  <q-step
                    :name="2"
                    title="业务组"
                    icon="fas fa-cube"
                    @click="step = 2"
                    active-icon="fas fa-cube"
                  >
                    <q-table
                      flat
                      dense
                      class="bg-white"
                      :data="dataGroup"
                      :columns="columnsGroup"
                      row-key="groupId"
                      separator="cell"
                      selection="multiple"
                      :selected.sync="selectedGroup"
                      :filter="searchFormGroup"
                      :pagination.sync="paginationGroup"
                      :rows-per-page-options="[3, 5, 10, 20]"
                      no-data-label="暂无数据"
                      table-class="h-custom"
                      @request="tableDataGet"
                    >
                      <template v-slot:header="props">
                        <q-tr :props="props" style="height:36px">
                          <q-th>
                            <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
                          </q-th>
                          <q-th v-for="col in props.cols" :key="col.name" :props="props">
                            {{ col.label }}
                          </q-th>
                        </q-tr>
                      </template>
                      <template v-slot:body="props">
                        <q-tr :props="props" style="height:36px">
                          <q-td width="52">
                            <q-checkbox dense v-model="props.selected" />
                          </q-td>
                          <q-td key="groupName" :props="props">{{ props.row.groupName }}</q-td>
                          <q-td key="groupCode" :props="props">{{ props.row.groupCode  }}</q-td>
                          <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
                        </q-tr>
                        <q-tr v-show="props.expand" :props="props">
                          <q-td colspan="100%">
                          </q-td>
                        </q-tr>
                      </template>
                      <template v-slot:pagination="props">
                        <q-pagination
                          v-model="paginationGroup.page"
                          color="blue"
                          :max-pages="5"
                          :max="pagesGroup"
                          :boundaryLinks="true"
                          :directionLinks="true"
                        />
                        共 {{ totalGroup }} 条
                      </template>
                    </q-table>
                  </q-step>
                </q-stepper>

              </div>
            </q-tab-panel>
          </q-tab-panels>
        </q-card-section>
        <q-separator class="absolute" style="bottom: 52px; left: 0"/>
        <q-card-actions align="right" class="absolute-bottom bg-white">
          <q-btn v-if="!addOrEditForm.id" flat label="保存并分配岗位" color="primary" :disable="loadingSave" :loading="loadingSingleSave" @click="saveSingleHandler">
            <q-tooltip anchor="top middle" self="bottom middle" :offset="[5, 5]" content-class="bg-black text-white">
              <div style="width:150px;font-size:11px">
                该操作会保存您在“用户属性”一栏填写的全部信息，并且不会关闭当前会话框，以便于您继续为该用户分配岗位等。
              </div>
            </q-tooltip>
          </q-btn>
          <q-space/>
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn flat label="保存" color="primary" :loading="loadingSave" @click="saveHandler" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import { indexOf, filter } from 'lodash'
import { required } from 'vuelidate/lib/validators'
import { transformToTreeFormat } from 'src/utils/fns'
// import { plusNumber, plusInteger } from 'src/utils/my.validators'
export default {
  name: 'User',
  data () {
    return {
      passwordDisable: true,
      searchToggle: false,
      searchForm: {
        loginName: '',
        password: '',
        phone: '',
        email: '',
        isNeedUpdatePassword: '',
        createTime: ''
      },
      selected: [],
      visibleColumns: [
        'action',
        'loginName',
        'password',
        'phone',
        'email',
        'isNeedUpdatePassword',
        'createTime'
      ],
      // 当加入 required: true 属性时  visibleColumns 对当前字段无效
      columns: [
        { name: 'action', align: 'center', label: '操作' },
        { name: 'loginName', field: 'loginName', align: 'left', label: '账户', sortable: true },
        { name: 'password', field: 'password', align: 'left', label: '密码', sortable: true },
        { name: 'email', field: 'email', align: 'left', label: '邮箱地址', sortable: true },
        { name: 'phone', required: true, label: '电话', align: 'left', field: 'phone' },
        { name: 'isNeedUpdatePassword', required: true, label: '首次登陆修改密码', align: 'left', field: 'isNeedUpdatePassword' },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
      ],
      data: [],
      total: 0,
      pagination: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10,
        sortBy: '',
        descending: ''
      },
      // dialog
      addOrEdit: 1, // 1 新增  2 修改
      loadingSave: false,
      loadingSingleSave: false,
      addOrEditDialog: false,
      maximizedToggle: false,
      addOrEditTab: 'tab1',
      saveUserRoleGroupLoading: false,
      addOrEditForm: {
        tenantId: '',
        loginName: '',
        password: '',
        email: '',
        phone: '',
        isNeedUpdatePassword: 0
      },
      // dialog 左侧 tree
      nodes: [],
      nodeSelected: '',
      nodeExpanded: [],
      nodeTicked: [],
      nodeHeader: '',
      nodeSelectedHeader: 'root',
      // dialog 右侧 table
      columnsRole: [
        { name: 'roleName', required: true, label: '角色名称', align: 'left', field: 'roleName', sortable: true },
        { name: 'roleCode', required: true, label: '角色编码', align: 'left', field: 'roleCode', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
      ],
      dataRole: [],
      totalRole: 0,
      paginationRole: {
        page: 1,
        rowsPerPage: 5,
        rowsNumber: 5,
        sortBy: '',
        descending: Boolean
      },
      searchToggleRole: false,
      searchFormRole: {
        roleName: '',
        roleCode: '',
        createTime: ''
      },
      selectedRole: [],
      columnsGroup: [
        { name: 'groupName', required: true, label: '业务组名称', align: 'left', field: 'groupName', sortable: true },
        { name: 'groupCode', required: true, label: '业务组编码', align: 'left', field: 'groupCode', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
      ],
      dataGroup: [],
      totalGroup: 0,
      paginationGroup: {
        page: 1,
        rowsPerPage: 5,
        rowsNumber: 5,
        sortBy: '',
        descending: Boolean
      },
      tenantOption: [],
      searchToggleGroup: false,
      searchFormGroup: {
        groupName: '',
        groupCode: '',
        createTime: ''
      },
      selectedGroup: [],
      // stepper
      step: 1
    }
  },
  computed: {
    pages () {
      return Math.ceil(this.total / this.pagination.rowsPerPage)
    },
    pagesRole () {
      return Math.ceil(this.totalRole / this.paginationRole.rowsPerPage)
    },
    pagesGroup () {
      return Math.ceil(this.totalGroup / this.paginationGroup.rowsPerPage)
    },
    isNodeSelected () {
      return !!this.nodeSelected
    }
  },
  validations: {
    addOrEditForm: {
      tenantId: { required },
      loginName: { required },
      password: { required },
      email: { required },
      phone: { required }
    }
  },
  watch: {
    'pagination.page' () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    },
    'paginationRole.page' () {
      this.nodeSelectedHandler(this.nodeSelected)
    },
    'paginationGroup.page' () {
      this.nodeSelectedHandler(this.nodeSelected)
    },
    step (step) {
      this.nodeSelectedHandler(this.nodeSelected)
    }
  },
  mounted () {
    this.init()
    this.getTenantType()
  },
  methods: {
    init () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    },
    async listGet (props) {
      let { page, rowsPerPage, sortBy, descending } = props.pagination, filter = props.filter
      await this.$api({
        method: 'post',
        url: '/mdm/user/query',
        params: {
          pageNo: page,
          pageSize: rowsPerPage,
          sort: sortBy,
          order: descending === true ? 'desc' : (descending === false ? 'asc' : ''),
          ...filter
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.total = data.total
          this.data = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.pagination.page = page
      this.pagination.rowsPerPage = rowsPerPage
      this.pagination.sortBy = sortBy
      this.pagination.descending = descending
    },
    add () {
      this.passwordDisable = false
      this.addOrEdit = 1
      this.addOrEditTab = 'tab1'
      this.addOrEditForm = {
        tenantId: '',
        loginName: '',
        password: '',
        email: '',
        phone: '',
        isNeedUpdatePassword: 0
      }
      this.$v.addOrEditForm.$reset()
      this.addOrEditDialog = true
    },
    async edit (row) {
      this.passwordDisable = true
      await Promise.all([
        this.$api({
          method: 'get',
          url: `/mdm/user/findById/${row.id}`,
          useLoadLayer: true,
          successCallback: ({ data }) => {
            console.log(data)
            this.addOrEditForm = { ...data }
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        }),
        this.nodesGet()
      ])
      await this.userStationGet()
      this.addOrEdit = 2
      this.addOrEditTab = 'tab1'
      this.$v.addOrEditForm.$reset()
      this.addOrEditDialog = true
    },
    async saveHandler () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        this.loadingSave = true
        await this.$api({
          method: 'put',
          url: '/mdm/userpermission/updateUserStation',
          params: {
            ...this.addOrEditForm,
            stationIds: this.nodeTicked.join(',')
          },
          emulateJSON: true,
          useNotify: true,
          successCallback: ({ data }) => {
            this.addOrEditDialog = false
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.loadingSave = false
        this.init()
      }
    },
    async saveSingleHandler () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        this.loadingSingleSave = true
        await Promise.all([
          this.$api({
            method: 'put',
            url: '/mdm/user/add',
            params: this.addOrEditForm,
            emulateJSON: true,
            useNotify: true,
            successCallback: ({ data }) => {
              this.addOrEditForm = { ...data }
            },
            errorCallback (err) {
              console.log('未处理的业务级error：', err)
            }
          }),
          this.nodesGet()
        ])
        await this.userStationGet()
        this.addOrEdit = 2
        this.addOrEditTab = 'tab2'
        this.loadingSingleSave = false
        this.init()
      }
    },
    delRow (row) {
      this.$q.dialog({
        title: '删除',
        message: `确认要删除角色：${row.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'delete',
          url: `/mdm/user/delete/${row.id}`,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.listGet({
          pagination: this.pagination,
          filter: this.searchForm
        })
      }).onCancel(() => {

      })
    },
    async nodesGet () {
      await this.$api({
        method: 'post',
        url: '/mdm/org/queryTree',
        useLoadLayer: true,
        successCallback: ({ data }) => {
          let arr = []
          data.map(item => {
            arr.push(item.id)
            if (item.itemList && item.itemList.length > 0) {
              item.itemList.map(item2 => {
                arr.push(item2.id)
              })
            }
          })
          this.nodeExpanded = arr
          this.nodeSelected = ''
          let nodes = transformToTreeFormat(data)
          this.nodes = this.nodesRecursive(nodes)
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    nodesRecursive (nodes) {
      nodes.map(item => {
        if (item.parentId === '0' && item.type === 1) {
          item.header = 'root'
          item.noTick = true
          item.selectable = false
        } else if (item.type === 1) {
          item.header = 'company'
          item.noTick = true
          item.selectable = false
        } else if (item.type === 2) {
          item.header = 'dep'
          item.noTick = true
          item.selectable = false
        } else {
          item.header = 'post'
          item.noTick = false
          item.selectable = true
        }
        if (item.itemList && item.itemList.length > 0) {
          item.children = item.itemList
          delete item.itemList
          this.nodesRecursive(item.children)
        }
      })
      return nodes
    },
    async userStationGet () {
      await this.$api({
        method: 'post',
        url: '/mdm/userpermission/queryStation',
        params: {
          userId: this.addOrEditForm.id
        },
        emulateJSON: true,
        successCallback: ({ data }) => {
          this.nodeTicked = data
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    async nodeSelectedHandler (nodeKey) {
      if (nodeKey) {
        let node = this.$refs['orgTree'].getNodeByKey(nodeKey)
        this.nodeSelectedHeader = node.header
        switch (this.nodeSelectedHeader) {
          case 'post':
            switch (this.step) {
              case 1:
                this.nodeHeader = 'Role'
                await this.tableDataGet({
                  pagination: this.paginationRole,
                  filter: this.searchFormRole
                })
                await this.tableSelectedGet()
                break
              case 2:
                this.nodeHeader = 'Group'
                await this.tableDataGet({
                  pagination: this.paginationGroup,
                  filter: this.searchFormGroup
                })
                await this.tableSelectedGet()
                break
            }
            break
        }
      }
    },
    async tableDataGet (props) {
      let { page, rowsPerPage, sortBy, descending } = props.pagination, filter = props.filter
      let otherQueryArgs = {}, url = ''
      switch (this.nodeHeader) {
        case 'Role':
          otherQueryArgs = { stationId: this.nodeSelected }
          url = '/mdm/rolestation/query'
          break
        case 'Group':
          otherQueryArgs = { stationId: this.nodeSelected }
          url = '/mdm/groupstation/query'
          break
        default:
          break
      }
      await this.$api({
        method: 'post',
        url: url,
        params: {
          pageNo: page,
          pageSize: rowsPerPage,
          sort: sortBy,
          order: descending === true ? 'desc' : (descending === false ? 'asc' : ''),
          ...filter,
          ...otherQueryArgs
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this[`total${this.nodeHeader}`] = data.total
          this[`data${this.nodeHeader}`] = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this[`pagination${this.nodeHeader}`].page = page
      this[`pagination${this.nodeHeader}`].rowsPerPage = rowsPerPage
      this[`pagination${this.nodeHeader}`].sortBy = sortBy
      this[`pagination${this.nodeHeader}`].descending = descending
    },
    tableSelectedGet () {
      let url = ''
      switch (this.nodeHeader) {
        case 'Role':
          url = '/mdm/userpermission/queryRole'
          break
        case 'Group':
          url = '/mdm/userpermission/queryGroup'
          break
        default:
          break
      }
      this.$api({
        method: 'post',
        url: url,
        params: {
          userId: this.addOrEditForm.id,
          stationId: this.nodeSelected
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          console.log(data)
          let selectRows = []
          data.map(s => {
            this[`data${this.nodeHeader}`].map(d => {
              if (s === d.roleId || s === d.groupId) {
                selectRows.push(d)
              }
            })
          })
          this[`selected${this.nodeHeader}`] = selectRows
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    saveUserRoleGroup () {
      let roleIdsArr = this.selectedRole.map(item => item.roleId)
      let groupIdsArr = this.selectedGroup.map(item => item.groupId)
      this.saveUserRoleGroupLoading = true
      this.$api({
        method: 'put',
        url: '/mdm/userpermission/updateUserRoleGroup',
        params: {
          id: this.addOrEditForm.id,
          stationId: this.nodeSelected,
          roleIds: roleIdsArr.join(','),
          groupIds: groupIdsArr.join(',')
        },
        emulateJSON: true,
        useNotify: true,
        successCallback: ({ data }) => {
          this.nodeSelectedHandler(this.nodeSelected)
          this.saveUserRoleGroupLoading = false
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    async getTenantType () {
      await this.$api({
        method: 'post',
        url: '/pp/tenant/query',
        parmas: {
          pageNo: 100,
          pageSize: 1
        },
        emulateJSON: true,
        successCallback: ({ data }) => {
          console.log(data)
          let arr = []
          let datas = data.list
          datas.forEach(item => {
            let o = {}
            o.label = item.name
            o.value = item.id
            arr.push(o)
          })
          this.tenantOption = arr
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    nodeSelectedClick (nodeSelected) {
      if (indexOf(this.nodeTicked, nodeSelected) > -1) {
        if (nodeSelected === this.nodeSelected) {
          this.nodeTicked = filter(this.nodeTicked, node => node !== nodeSelected)
        }
      } else {
        this.nodeTicked.push(nodeSelected)
      }
    }
  }
}
</script>
